<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <!--    content属性设置了视口的宽度和初始缩放比例。
width=device表示视口宽度应与设备的屏幕宽度相等
initial-scale=1表示初始缩放比例为1，即页面以其原始大小显示。-->
    <meta name="viewpoint" content="width=device,initial-scale=1">
    <link href="font-awesome-4.7.0/css/font-awesome.css" rel="stylesheet">
    <link href="reset.css" rel="stylesheet">
    <link href="icon.css" rel="stylesheet">
    <link href="businessInfo.css" rel="stylesheet">
    <title>饿了么 商家信息</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>

<body>
    <div class="wrapper">
        <!--    header部分-->
        <header>
            <p>商家信息</p>
        </header>
        <!--    商家logo部分-->
        <div class="business-logo">
            <img id="businessImg">
        </div>
        <div class="business-info">
        </div>
        <ul class="food">
        </ul>
        <!--    购物车部分-->
        <div class="cart">
            <!--        存放购物车左侧内容-->
            <div class="cart-left">
                <!--            存放购物车图标和数量-->
                <div class="cart-left-icon">
                    <!--                显示购物车图标-->
                    <i class="fa fa-shopping-cart"></i>
                    <div class="cart-left-icon-quantity" id="totalQuantity">0</div>
                </div>
                <div class="cart-left-info">
                    <p>&#165;<span id="totalPrice"></span></p>
                    <p id="deliveryPrice"></p>
                </div>
            </div>
            <div class="cart-right">
                <!--            不够起送费-->
                <div class="cart-right-item start" style="display: none;">&#165;<span id="startPrice"></span>起送</div>
                <!--            够起送费-->
                <div class="cart-right-item" style="display: none;" onclick="toOrder()" id="pay">去结算</div>
            </div>
        </div>
    </div>
</body>
<script>
    function getURLParameter(name) {
        // 获取 URL 中的查询字符串部分
        var urlParams = new URLSearchParams(window.location.search);
        // 返回指定参数的值
        return urlParams.get(name);
    }

    function getUserInfo() {
        // 从 cookie 中读取用户信息
        var userInfoString = $.cookie('userInfo');
        if (userInfoString) {
            return JSON.parse(userInfoString);
        } else {
            window.location.href = 'login.html';
        }
    }

    function getBusiness(shopId) {
        $.ajax({
            url: 'http://127.0.0.1:8081/shop/getShopById?shopId=' + shopId, // 替换为实际的注册 API URL
            type: 'GET',
            contentType: 'application/json; charset=UTF-8', // 设置内容类型为 JSON
            data: {},
            success: function (res) {
                if (res.flag) {
                    console.log(res)
                    $('#businessImg').attr('src', res.data.shopImg)
                    var html = [];
                    html.push('<h1 id="">' + res.data.shopName + '</h1>')
                    html.push('<p>&#165;' + res.data.startPrice + '起送 &#165;' + res.data.deliveryPrice + '配送</p>')
                    html.push('<p>' + res.data.shopExplain + '</p>')
                    $('.business-info').html(html.join(''))
                    $('#deliveryPrice').html('另需配送费' + res.data.deliveryPrice + '元')
                    $("#startPrice").html(res.data.startPrice)
                } else {
                    alert(res.message)
                }
            },
            error: function (xhr, status, error) {
                alert('查询失败：' + xhr.statusText);
            }
        });
    }

    function listFoods(shopId) {
        $.ajax({
            url: 'http://127.0.0.1:8081/food/getFoodByShopId?shopId=' + shopId, // 替换为实际的注册 API URL
            type: 'GET',
            contentType: 'application/json; charset=UTF-8', // 设置内容类型为 JSON
            data: {},
            success: function (res) {
                if (res.flag) {
                    console.log(res)
                    var html = []
                    for (var i = 0; i < res.data.length; i++) {
                        html.push('<li>                                        ')
                        html.push('	<div class="food-left">                    ')
                        html.push('		<img src="' + res.data[i].foodImg + '">               ')
                        html.push('		<div class="food-left-info">           ')
                        html.push('			<h3>' + res.data[i].foodName + '</h3>          ')
                        html.push('			<p>' + res.data[i].foodExplain + '</p>                    ')
                        html.push('			<p>&#165;' + res.data[i].foodPrice + '</p>                    ')
                        html.push('		</div>                                 ')
                        html.push('	</div>                                     ')
                        html.push('	<div class="food-right">                   ')
                        html.push('		<div>                                  ')
                        html.push('			<i class="fa fa-minus-circle" onclick="removeCart(' + res.data[i].foodId + ', ' + shopId + ')"></i> ')
                        html.push('		</div>                                 ')
                        html.push('		<p><span id="foodCount' + res.data[i].foodId + '">0</span></p>                  ')
                        html.push('		<div>                                  ')
                        html.push('			<i class="fa fa-plus-circle" onclick="addCart(' + res.data[i].foodId + ', ' + shopId + ')"></i>  ')
                        html.push('		</div>                                 ')
                        html.push('	</div>                                     ')
                        html.push('</li>                                       ')
                    }
                    $('.food').html(html.join(''))
                    listCarts(shopId);
                } else {
                    alert(res.message)
                }
            },
            error: function (xhr, status, error) {
                alert('查询失败：' + xhr.statusText);
            }
        });
    }

    function listCarts(shopId) {
        $.ajax({
            url: 'http://127.0.0.1:8081/cart/listCart',
            type: 'POST',
            contentType: 'application/json; charset=UTF-8', // 设置内容类型为 JSON
            data: JSON.stringify({
                userId: getUserInfo().userId,
                shopId: shopId
            }),
            success: function (res) {
                if (res.flag) {
                    console.log(res)
                    var totalPrice = 0;
                    var totalQuantity = 0;
                    for (var i = 0; i < res.data.length; i++) {
                        $("#foodCount" + res.data[i].foodId).text(res.data[i].quantity);
                        totalPrice += res.data[i].food.foodPrice * res.data[i].quantity;
                        totalQuantity += res.data[i].quantity;
                    }
                    $('#totalPrice').html(totalPrice);
                    $('#totalQuantity').html(totalQuantity);
                    // 如果总价大于起送费，显示结算按钮，否则显示起送价
                    if (totalPrice >= parseInt($("#startPrice").text())) {
                        $('.cart-right-item.start').css('display', 'none');
                        $('#pay').css('display', 'flex');
                    } else {
                        $('.cart-right-item.start').css('display', 'flex');
                        $('#pay').css('display', 'none');
                    }
                } else {
                    alert(res.message)
                }
            },
            error: function (xhr, status, error) {
                alert('查询失败：' + xhr.statusText);
            }
        });
    }

    function addCart(foodId, shopId) {
        $.ajax({
            url: 'http://127.0.0.1:8081/cart/saveCart',
            type: 'POST',
            async: false,
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({
                userId: getUserInfo().userId,
                foodId: foodId,
                shopId: shopId,
                quantity: 1
            }),
            success: function (res) {
                if (res.flag) {
                    var foodCount = parseInt($("#foodCount" + foodId).text()) + 1
                    $("#foodCount" + foodId).text(foodCount);
                    listCarts(shopId);
                } else {
                    alert(res.message)
                }
            },
            error: function (xhr, status, error) {
                alert('查询失败：' + xhr.statusText);
            }
        });
    }

    function removeCart(foodId, shopId) {
        var foodCount = parseInt($("#foodCount" + foodId).text()) - 1;
        if (foodCount < 0) {
            return;
        }
        $.ajax({
            url: 'http://127.0.0.1:8081/cart/removeCart',
            type: 'POST',
            async: false,
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({
                userId: getUserInfo().userId,
                foodId: foodId,
                shopId: shopId,
                quantity: 1
            }),
            success: function (res) {
                if (res.flag) {
                    var foodCount = parseInt($("#foodCount" + foodId).text()) - 1
                    $("#foodCount" + foodId).text(foodCount);
                    listCarts(shopId);
                } else {
                    alert(res.message)
                }
            },
            error: function (xhr, status, error) {
                alert('查询失败：' + xhr.statusText);
            }
        });
    }

    function toOrder() {
        getUserInfo();
        // 如果总价格大于0，允许跳转到订单页面，否则提示请先选购菜品再下单
        if (parseInt($("#totalPrice").text()) > 0) {
            window.location.href = 'order.html?shopId=' + getURLParameter('id');
        } else {
            alert('请先选购菜品再下单');
        }
    }

    $(document).ready(function () {
        var shopId = getURLParameter('id');
        if(shopId == null || shopId == '') {
            alert('参数错误');
            return;
        }
        console.log(shopId);
        getBusiness(shopId);
        listFoods(shopId);
    });
</script>

</html>